/*
 * @Author: your name
 * @Date: 2020-09-15 16:26:00
 * @LastEditTime: 2020-12-14 19:15:24
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \inventory-apie:\hjimi\人脸\html\face-recognition\src\utils\request.js
 */
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router from "../router"
import qs from "qs"
// import cookies from 'js-cookie'

let hash = window.location.hash
const service = axios.create({
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  // baseURL: process.env.API_ROOT, // axios.defaults.baseURL = process.env.API_ROOT
  // baseURL: '/api', //nginx代理需要加'/api'
  withCredentials: true,
  timeout: 60000
})


service.interceptors.request.use(config => {
  /**
 * @description: 配置请求头
 */ 
    let token = store.state.loginModule.token,
        conType = config.headers['Content-Type']
    
    config.headers['Authorization'] = token ? getToken() : 'token'
    // config.headers['Content-Type'] =  'multipart/form-data'
    
// 拦截是否登录状态
    if (!token || token == null || token == undefined || token === 'token') {
      if(router.options.routes[0].name !== 'login') {
      store.dispatch("logout")
      }
    }
    
  /**
 * @description: 凡是post发送的请求一律转为url参数形式（formData）,排除页面中自定义发送的new Formdata() === 'object
 */ 
    if (config.method.toUpperCase() === 'POST') {
      if(config.data !== undefined && config.data !== null 
         && !config.data.append //排除是否为自定义发送的new Formdata数据
        ) {
        if(conType && (conType.indexOf('application/json') && conType.indexOf("multipart/form-data")) === -1){
         config.data = qs.stringify(config.data)
      }
    } 
  }
    return config
  }, error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(response => {
     let code = response.data.code || 0,
         msg =  response.data.msg,
         config = response.config
         
/**
 * @description: 处理api错误码(不同的码，有不同的提示和操作),错误码文档在 /README/API和错误码.md
 */      
      if(code !== 0) {
        if(code === 10109){ //token过期
           removeToken() 
        } else if(code === 10110) { //无token
           Message('请登录', 6000), router.push({path:'/'})  

        } else if(code === 10103) {
           Message.error("邮箱验证码有误！", 5000)

        } else if(code === 10102) {
          Message.error("用户名或邮箱有误", 5000)
          
        } else if(  //处理图片上传code（图片质量评估code）
             code === 11001 //模糊
          || code === 11002 //强光照  
          || code === 11003 //弱光照
          || code === 11004 //口罩遮挡
          || code === 11005 //墨镜遮挡
          || code === 11006 //手遮挡
          || code == 11007  //其他遮挡
          || code === 11008 //张口
          || code === 11009 //闭眼
          || code === 11010 //多人脸
          || code === 11011 //无人脸
          || code === 11012 //姿态不符
          || code === 11013 //人脸过小
          ) { 
          new function () {
            if(hash.includes('/propertiesShow')) setTimeout(() => { router.go(0) }, 2000) //属性页面出错刷新
           Message({
             message: msg + '！请另选重试',
             type: "warning",
             showClose: true,
             duration: 0
           })
          } 
         } else if(code === 10007 || code === 10008 || code === 10009 || code === 1000) {  //服务调用失败
          Message.error(msg, 6000)
          
         } else if(code === 10201 || code === 10203 || code === 10107) {
          Message.warning(msg, 5000)
          
         } else if(code === 10001) {
           location.hash.includes('faceManagement') ? String : Message.warning(msg) //针对faceManagement页面，取消库码不能为空提示
           
         } else if(code === 10108) {
          if(hash.includes('/deviceControl')) Message.warning(`${config.params.datas} ${msg}`)  //针对deviceControl页面，提示加上sn

         } else{
          Message.warning(msg)
         }
    }
    console.log(response)
    return response.data;
 }, error => { 
   
  /**
 * @description: 操作http状态码
 */
    if (error && error.response) {
      let errRes = error.response
      switch (errRes.status) {
        case 400:
          Message({
            message: "参数有误（400）,请重试",
            type: "warning",
            duration: 5 * 1000
          })
          break
        case 404:
          Message({
            message: `请求地址：${ errRes.data.path } 不存在（404）`,
            type: "error",
            duration: 5 * 1000
          })
          console.log(errRes)
          break
        case 401:
          if(window.location.href !== window.location.origin + '/#/') {
            removeToken()
          }
          break
        case 500:
          Message({
            message: `请求地址：${ errRes.data.path } 服务器异常（500）`,
            type: "error",
            duration: 10 * 1000
          })
          break
          default: Message.error(error.message, 5000)
      }
    }

    if (error.toString().indexOf('Error: timeout') !== -1) {  // 请求超时提示
      Message.error('请求超时，请刷新重试！', 60000)
    }
    return Promise.reject(error)
  }
)
export default service